<template>
  <view class="post-item" @click="goToDetail">
    <!-- 用户信息 -->
    <view class="user-info">
      <image 
        class="avatar" 
        :src="post.avatar" 
        mode="aspectFill"
        @click.stop="goToUserPage"
      />
      <view class="user-meta">
        <view class="nickname">{{ post.nickname }}</view>
        <view class="time">{{ formatTime(post.createTime) }}</view>
      </view>
      <view class="tag" v-if="post.tag && post.tag !== 'all'">{{ getTagName(post.tag) }}</view>
    </view>
    
    <!-- 内容 -->
    <view class="content">{{ post.content }}</view>
    
    <!-- 图片 -->
    <view class="images" v-if="post.images && post.images.length > 0">
      <view class="image-grid" :class="getImageLayoutClass(post.images.length)">
        <image 
          v-for="(image, index) in post.images" 
          :key="index" 
          :src="image" 
          mode="aspectFill" 
          class="image-item"
          @click.stop="previewImage(index)"
        />
      </view>
    </view>
    
    <!-- 操作栏 -->
    <view class="action-bar">
      <view class="action-item" @click.stop="handleLike">
        <text class="iconfont" :class="post.isLiked ? 'icon-like-filled' : 'icon-like'">{{ post.isLiked ? '❤️' : '🤍' }}</text>
        <text class="count">{{ post.likesCount }}</text>
      </view>
      <view class="action-item" @click.stop="goToDetail">
        <text class="iconfont icon-comment">💬</text>
        <text class="count">{{ post.commentsCount }}</text>
      </view>
      <view class="action-item" v-if="isOwner" @click.stop="handleDelete">
        <text class="iconfont icon-delete">🗑️</text>
        <text class="count">删除</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useStore } from 'vuex';
import { POST_TAGS } from '../../mock/community';

const store = useStore();
const emit = defineEmits(['delete', 'like']);

// 从props接收动态数据
const props = defineProps({
  post: {
    type: Object,
    required: true
  }
});

// 是否是动态所有者（用于显示删除按钮）
// 实际项目中应该从用户状态中获取当前用户ID进行比较
const isOwner = computed(() => {
  // 假设当前用户ID为1
  return props.post.userId === 1 && !props.post.isAnonymous;
});

// 获取标签名称
const getTagName = (tagId) => {
  const tagList = store.getters['community/tagList'];
  const tag = tagList.find(t => t.id === tagId);
  return tag ? tag.name : '';
};

// 根据图片数量获取布局类名
const getImageLayoutClass = (count) => {
  if (count === 1) return 'single';
  if (count === 2) return 'double';
  if (count === 3) return 'triple';
  if (count === 4) return 'quad';
  return 'grid';
};

// 格式化时间
const formatTime = (timestamp) => {
  const now = Date.now();
  const diff = now - timestamp;
  
  // 一分钟内
  if (diff < 60 * 1000) {
    return '刚刚';
  }
  
  // 一小时内
  if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`;
  }
  
  // 一天内
  if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
  }
  
  // 一周内
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`;
  }
  
  // 超过一周
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 预览图片
const previewImage = (index) => {
  uni.previewImage({
    current: index,
    urls: props.post.images
  });
};

// 跳转到动态详情页
const goToDetail = () => {
  uni.navigateTo({
    url: `/pages/community/detail?id=${props.post.id}`
  });
};

// 跳转到用户主页
const goToUserPage = () => {
  // 如果是匿名发布，不跳转
  if (props.post.isAnonymous) {
    return;
  }
  
  uni.navigateTo({
    url: `/pages/community/user?id=${props.post.userId}`
  });
};

// 点赞/取消点赞
const handleLike = async () => {
  const isLike = !props.post.isLiked;
  
  try {
    await store.dispatch('community/likePost', {
      postId: props.post.id,
      isLike
    });
    
    emit('like', {
      postId: props.post.id,
      isLike
    });
  } catch (error) {
    console.error('点赞操作失败', error);
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    });
  }
};

// 删除动态
const handleDelete = () => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这条动态吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await store.dispatch('community/deletePost', props.post.id);
          
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          });
          
          emit('delete', props.post.id);
        } catch (error) {
          console.error('删除动态失败', error);
          uni.showToast({
            title: '删除失败，请重试',
            icon: 'none'
          });
        }
      }
    }
  });
};
</script>

<style lang="scss" scoped>
.post-item {
  margin: 12px;
  padding: 18px;
  background-color: #ffffff;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  
  .user-info {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    
    .avatar {
      width: 46px;
      height: 46px;
      border-radius: 50%;
      margin-right: 12px;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
      border: 2px solid #ffffff;
    }
    
    .user-meta {
      flex: 1;
      
      .nickname {
        font-size: 16px;
        font-weight: 600;
        color: #333333;
        margin-bottom: 4px;
      }
      
      .time {
        font-size: 12px;
        color: #999999;
      }
    }
    
    .tag {
      font-size: 12px;
      color: #007aff;
      background-color: rgba(0, 122, 255, 0.1);
      padding: 4px 10px;
      border-radius: 12px;
      font-weight: 500;
      box-shadow: 0 1px 3px rgba(0, 122, 255, 0.1);
    }
  }
  
  .content {
    font-size: 16px;
    color: #333333;
    line-height: 1.6;
    margin-bottom: 16px;
    word-break: break-all;
    letter-spacing: 0.3px;
  }
  
  .images {
    margin-bottom: 16px;
    
    .image-grid {
      display: flex;
      flex-wrap: wrap;
      
      &.single {
        .image-item {
          width: 80%;
          height: 220px;
          border-radius: 14px;
          box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
        }
      }
      
      &.double {
        .image-item {
          width: calc(50% - 6px);
          height: 140px;
          margin-right: 12px;
          margin-bottom: 0;
          border-radius: 12px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
          
          &:nth-child(2n) {
            margin-right: 0;
          }
        }
      }
      
      &.triple {
        .image-item {
          width: calc(33.33% - 8px);
          height: 110px;
          margin-right: 12px;
          border-radius: 10px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
          
          &:nth-child(3n) {
            margin-right: 0;
          }
        }
      }
      
      &.quad, &.grid {
        .image-item {
          width: calc(50% - 6px);
          height: 110px;
          margin-right: 12px;
          margin-bottom: 12px;
          border-radius: 10px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
          
          &:nth-child(2n) {
            margin-right: 0;
          }
        }
      }
    }
  }
  
  .action-bar {
    display: flex;
    border-top: 1px solid #f2f2f2;
    padding-top: 14px;
    margin-top: 4px;
    
    .action-item {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      color: #666666;
      height: 40px;
      position: relative;
      
      &:after {
        content: '';
        position: absolute;
        right: 0;
        top: 20%;
        height: 60%;
        width: 1px;
        background-color: #f2f2f2;
      }
      
      &:last-child:after {
        display: none;
      }
      
      .iconfont {
        margin-right: 6px;
        font-size: 18px;
      }
      
      .count {
        font-size: 14px;
      }
      
      &:active {
        opacity: 0.7;
        background-color: #f9f9f9;
        border-radius: 8px;
      }
      
      &.icon-like-filled {
        color: #ff5a5f;
      }
    }
  }
}
</style>
